package com.tiniplanet.webgate.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.tiniplanet.webgate.common.WebConstants;
import com.tiniplanet.webgate.entity.Employee;
import com.tiniplanet.webgate.service.EmployeeService;

@Controller
@RequestMapping("/admin")
public class AdminController extends PageController {

	private static Logger logger = Logger.getLogger(AdminController.class);

	private EmployeeService employeeService;

	@Autowired
	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public AdminController() {
		addItemToTabMenu("/admin/users/", "User Management", "dashboard", true);
		
		addItemToSideMenu("/home", "General", "home", false);
		addItemToSideMenu("/admin/", "Admin", "form", true);
	}

	@RequestMapping("/")
	public String adminHome() {
		return "redirect:/admin/users/";
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/listUsers")
	public String setupUserList(ModelMap modelMap, @RequestParam("page") String page) {
		logger.debug("prepare user list");

		int pageNum = 1;
		try {
			pageNum = Integer.valueOf(page);
			if (pageNum < 1) {
				pageNum = 1;
			}
		} catch (NumberFormatException nfe) {
			logger.error("Invalid page number");
		}

		List<Employee> employees = null;
		long total = employeeService.count();
		if (total > 0) {
			employees = employeeService.getPage(pageNum);
		}

		// build model
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", total);
		data.put("employees", employees);
		data.put("pageIndex", pageNum);
		data.put("totalPage", Math.ceil((double) total / WebConstants.USER_LIST_PAGE_SIZE));

		setModel(modelMap, data);
		setMenu(modelMap);

		return "listusers";
	}

}
